package com.k.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.k.demo.entity.CustomerUser;
import com.k.demo.entity.FoodKind;
import com.k.demo.entity.GoodOrder;
import com.k.demo.entity.GoodOrderDetail;
import com.k.demo.service.CustomerUserService;
import com.k.demo.service.GoodOrderService;
import com.k.demo.service.PowerDistributionService;
import com.k.demo.service.RedBagRecordService;
import com.k.demo.service.ShoppingCartService;
import com.k.demo.service.VipService;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class CustomerUserController {

	@Autowired
	private CustomerUserService customeruserService;
	@Autowired
	private ShoppingCartService shoppingcartService;
	@Autowired
	private PowerDistributionService powerdistributionService;
	@Autowired
	private RedBagRecordService redBagRecordService;
	@Autowired
	private GoodOrderService goodOrderService;
	@Autowired
	private VipService vipService;

	@RequestMapping("/login")
	public Object login(@RequestParam("user_msg") String user_msg, @RequestParam("user_pwd") String user_pwd,
			HttpServletRequest request) {

		CustomerUser user = (CustomerUser) customeruserService.login(user_msg, user_pwd);

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("isLogin", false);

		if (user != null) {
			map.put("isLogin", true);

			request.getSession().setAttribute("loginUser", user);
			map.put("isAdmin", false);
			int[] i = { 2, 3, 4, 5, 6 };
			for (int j = 0; j < i.length; j++) {
				if (user.getUser_kind().equals(j)) {
					map.put("isAdmin", true);
				}
			}
			CustomerUser loginuser = (CustomerUser) request.getSession().getAttribute("loginUser");

			System.out.println("当前session中user" + loginuser.toString());
		}

		return map;

	}

	@RequestMapping("/logout")
	public Object logout(HttpServletRequest request) {
		request.getSession().removeAttribute("loginUser");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", "退出登录");
		return map;
	}

	@Value("${lc.upload.path}")
	private String uploadPath;

	@RequestMapping("/getuserinfo")
	public Object getCustomerUser(@RequestParam("userid") int userid) {

		return customeruserService.getCustomerUserByUserid(userid);
	}

	@RequestMapping("/changeuserinfo")
	public Object changeUserinfo(@RequestBody CustomerUser customerUser) {

		return customeruserService.updateCustomerUser(customerUser);
	}

	@RequestMapping("/changenowuserinfo")
	public Object changeNowUserinfo(@RequestBody CustomerUser customerUser,HttpServletRequest request) {
		
		request.getSession().setAttribute("loginUser", customerUser);
		
		return customeruserService.updateCustomerUser(customerUser);
	}
	
	@RequestMapping("/deluser")
	public Object deleteUser(int userid) {

		return customeruserService.deleteCustomerUser(userid);
	}

	@RequestMapping("/upload")
	public Object uploadFile(@RequestParam("multipartFile") MultipartFile multipartFile) {
		String fileName = UUID.randomUUID().toString().replaceAll("-", "") + multipartFile.getOriginalFilename();
		File file = null;
		try {
			file = new File(uploadPath + "/" + fileName);
			multipartFile.transferTo(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(file.exists());
		return "ok";
	}

	@RequestMapping("/register")
	public Object register(@RequestBody CustomerUser customeruser) {

		int user_id = customeruserService.insertCustomerUser(customeruser);
		boolean result = shoppingcartService.insertShoppingCart(user_id);
		Map<String, Object> map = new HashMap<String, Object>();
		if (result) {
			map.put("Insert", true);
		} else {
			map.put("Insert", false);
		}

		return map;
	}

	// 这边加入当前用户的 订单数量 红包记录数量 待评价数量
	@RequestMapping("/getlogin")
	public Object getLoginUser(HttpServletRequest request) {

		Map<String, Object> map = new HashMap<String, Object>();

		CustomerUser loginuser = (CustomerUser) request.getSession().getAttribute("loginUser");

		if (loginuser == null) {
			map.put("err", "您还没有登录");
		} else {
			Integer user_id = loginuser.getUser_id();
			// loginuser.setUser_password("******");
			map.put("loginUser", loginuser);
			// 获取红包数量
			map.put("redRecordAmount", redBagRecordService.getUserRedBagRecordAmount(user_id));
			// 获取当前用户所有订单数量
			map.put("allOrderAmount", goodOrderService.getAllOrderAmountByUserId(user_id));
			// 获取当前用户未评价订单数量
			map.put("notEvaluationOderAmount", goodOrderService.getNotEvaluationOrderAmountByUserId(user_id));
			// 获取当前用户会员等级
			map.put("vipLv", vipService.getByUserId(user_id));
		}
		return map;
	}

	// 管理员部分1 用户信息管理,注意不是当前用户的权限，而是管理员查询某个用户的权限,暂时不写，先看看前端想怎么实现
	@RequestMapping("/powerquery") // 查该用户的权限，带名字
	public Object getPower(@RequestBody Map<String, Object> map) {

		Map<String, Object> rmap = new HashMap<String, Object>();

		rmap.put("powerdistributionlist",
				powerdistributionService.getPowerDistributeByUserId((Integer) map.get("user_id")));

		return rmap;
	}

	@RequestMapping("/powerquerybyname") // 查该用户的权限，带名字
	public Object getPowerByName(@RequestBody Map<String, Object> map) {

		Map<String, Object> rmap = new HashMap<String, Object>();
		PageHelper.startPage((int) map.get("pageNum"), (int) map.get("pageSize"));
		List<Integer> user_id = customeruserService.getIdByName((String) map.get("user_true_name"));
		if (user_id.size() != 0) {
			PageInfo pageinfo = new PageInfo<>(customeruserService.getByIdList(user_id), (int) map.get("pageSize"));
			rmap.put("powerdistributionlist", pageinfo);
		} else {
			if(map.get("user_true_name")!=null && map.get("user_true_name")!="") {
				rmap.put("err", "没有此用户"); 
				return rmap; 
			}
			user_id = powerdistributionService.getAllUserId();// 如果没有，重新给数组赋值，查全部用户
			PageInfo pageinfo = new PageInfo<>(customeruserService.getByIdList(user_id), (int) map.get("pageSize"));
			rmap.put("powerdistributionlist", pageinfo);
		}

		return rmap;
	}

	@RequestMapping("/getbynameandkind") // 根据真实姓名和类别查 分页
	public Object getByNameAndKind(@RequestBody Map<String, Object> map) {

		CustomerUser user = new CustomerUser();
		user.setUser_true_name((String) map.get("user_true_name"));
		user.setUser_kind((Integer) map.get("user_kind"));

		Map<String, Object> rmap = new HashMap<String, Object>();

		PageHelper.startPage((int) map.get("pageNum"), (int) map.get("pageSize"));

		List<CustomerUser> userlist = customeruserService.getCustomerUserByUserNameAndUserKind(user);

		PageInfo pageinfo = new PageInfo<>(userlist, (int) map.get("pageSize"));

		rmap.put("userList", pageinfo);

		return rmap;
	}

	@RequestMapping("/powermodify") // 参考goodorderdetail 传参以那种形式为模板
	public Object modifyPower(@RequestBody String modify_msg) {

		Map<String, Object> map = new HashMap<String, Object>();

		JSONObject jsonObject = JSON.parseObject(modify_msg);

		int user_id = JSON.parseObject(jsonObject.getString("user_id"), Integer.class);

		List<Integer> powerArr = JSON.parseArray(jsonObject.getString("power_arr"), Integer.class);

		powerdistributionService.clearPower(user_id);
		// 先清除权限，再重新赋值
		map.put("addnum", powerdistributionService.grantPowerToUser(user_id, powerArr));

		return map;
	}

//	@RequestMapping("/addadmin")////修改
//	public Object addAdmin(@RequestBody String add_msg) {
//		
//		Map<String,Object> map = new HashMap<String, Object>();
//		
//		JSONObject jsonObject = JSON.parseObject(add_msg);
//		//用户对象需要以下信息
//		//String user_name, String user_nickname, String user_password, String user_true_name,
//		//String birthday, String sex, String telephone
//		CustomerUser user = new CustomerUser();
//		//权限表传对应的ID
//		List<Integer> powerlist = JSON.parseArray("powerlist", Integer.class);
//		//此处前端请求的时候需要将用户种类写死，即写成管理员类型
//		int count=customeruserService.insertCustomerUser(user);
//		int user_id = user.getUser_id();
//		map.put("inserted_user_id", user_id);
//		map.put("powernum", powerdistributionService.grantPowerToUser(user_id, powerlist));
//		
//		return map;
//	}
//	传的可以是user_id也可以是user_name
	@RequestMapping("/query")
	public Object userquery(@RequestParam String user_msg) {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("user", customeruserService.getCustomerUserByIdOrName(user_msg));

		return map;
	}

	// 获取全部用户，不分页
	@RequestMapping("/getall")
	public Object getAllUser() {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("UserList", customeruserService.getAll());

		return map;
	}

	@RequestMapping("/getall/page")
	public Object getAllUserbypage(@RequestParam int pagenum, @RequestParam int pagesize) {

		Map<String, Object> map = new HashMap<String, Object>();
		PageHelper.startPage(pagenum, pagesize);

		List<CustomerUser> userlist = customeruserService.getAll();

		PageInfo pageinfo = new PageInfo<>(userlist, pagesize);

		map.put("userList", pageinfo);

		return map;
	}

	// 分页查询,页数,每页数据数,用户类型,数据数前端可以写死了传过来
	@RequestMapping("/listquery")
	public Object userlistquery(@RequestParam int pagenum, @RequestParam int pagesize, @RequestParam int user_kind) {

		Map<String, Object> map = new HashMap<String, Object>();

		PageHelper.startPage(pagenum, pagesize);

		List<CustomerUser> userlist = customeruserService.getCustomerUserByKind(user_kind);

		PageInfo pageinfo = new PageInfo<>(userlist, pagesize);

		map.put("userList", pageinfo);

		return map;
	}

	@RequestMapping("/delete")
	public Object userdelete(@RequestParam int user_id) {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("deletenum", customeruserService.deleteCustomerUser(user_id));

		return map;

	}

	@RequestMapping("/deleteforeach")
	public Object userdeleteforeach(@RequestBody String customerlist) {

		JSONObject jsonObject = JSON.parseObject(customerlist);

		List<Integer> userlist = JSON.parseArray(jsonObject.getString("delete_list"), Integer.class);

		int count = customeruserService.deleteForEach(userlist);

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("deletenum", count);

		return map;

	}

	// 查找所有的骑手 骑手的kind是6
	@RequestMapping("/searchByKind")
	public Object searchCarrier(@RequestParam("user_kind") Integer user_kind) {

		Map<String, Object> map = new HashMap<String, Object>();

		map.put("carriersList", customeruserService.getCustomerUserByKind(user_kind));

		return map;

	}
}
